﻿using Abp.Application.Services;
using Senparc.Weixin;
using Senparc.Weixin.Entities;
using Senparc.Weixin.Helpers;
using Senparc.Weixin.TenPayV3;
using Senparc.Weixin.TenPayV3.Apis;
using Senparc.Weixin.TenPayV3.Apis.BasePay;
using Senparc.Weixin.TenPayV3.Entities;
using Senparc.Weixin.TenPayV3.Helpers;
using SportsPlatform.Base;
using SportsPlatform.Consts;
using SportsPlatform.Dto.WeiXinPay;
using SportsPlatform.Query.WeiXinPay;
using SportsPlatform.WeiXinPay.IWeiXinPay;
using SportsPlatform.HttpRequest;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;

namespace SportsPlatform.WeiXinPay.WeiXinPay
{
    /// <summary>
    /// 微信支付小程序调用实现类
    /// </summary>
    [RemoteService(false)]
    public class WeiXinTenPayV3Service : SportsPlatformAppServiceBase, IWeiXinTenPayV3Service
    {
        private static TenPayV3Info _tenPayV3Info;

        /// <summary>
        /// 获取配置参数
        /// </summary>
        public static TenPayV3Info TenPayV3Info
        {
            get
            {
                if (_tenPayV3Info == null)
                {
                    var key = TenPayHelper.GetRegisterKey(Config.SenparcWeixinSetting);

                    _tenPayV3Info =
                        TenPayV3InfoCollection.Data[key];
                }
                return _tenPayV3Info;
            }
        }

        private readonly ISenparcWeixinSettingForTenpayV3 _tenpayV3Setting;

        private readonly BasePayApis _basePayApis;
        //public WeiXinTenPayV3Service()
        //{
        //    _tenpayV3Setting = Senparc.Weixin.Config.SenparcWeixinSetting.TenpayV3Setting;
        //    _basePayApis = new BasePayApis(_tenpayV3Setting);
        //}
        /// <summary>
        /// 构造
        /// </summary>
        public WeiXinTenPayV3Service(IHttpContextAccessor context) : base(context)
        {
            _tenpayV3Setting = Senparc.Weixin.Config.SenparcWeixinSetting.TenpayV3Setting;
            _basePayApis = new BasePayApis(_tenpayV3Setting);
        }
        /// <summary>
        ///  根据Code获取OpenId
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>

        public GetCodeToOpenIdDto GetCodeToOpenId(GetCodeToOpenIdQuery query)
        {
            GetCodeToOpenIdDto dto = new GetCodeToOpenIdDto();
            try
            {
                if (string.IsNullOrEmpty(query.Code))
                {
                    dto.IsSuccess = false;
                    dto.Code = HttpResultCode.Fail;
                    dto.Message = "您拒绝了授权！";
                    return dto;
                }

                //通过，用code换取access_token
                var openIdResult = WeiXinApi.Jscode2Session(TenPayV3Info.AppId, TenPayV3Info.AppSecret, query.Code);
                if (openIdResult.Success != true)
                {
                    dto.IsSuccess = false;
                    dto.Code = HttpResultCode.Fail;
                    dto.Message = "错误：" + openIdResult.ErrorMessage;
                }
                else
                {
                    dto.IsSuccess = true;
                    dto.Code = HttpResultCode.Success;
                    dto.Message = "授权验证成功！";
                    dto.OpenId = openIdResult.OpenId;
                }
            }
            catch (Exception ex)
            {
                dto.IsSuccess = false;
                dto.Code = HttpResultCode.Error;
                dto.Message = ex.Message.ToString(); ;
            }
            return dto;
        }

        /// <summary>
        /// 预下单
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>

        public async Task<ResultDto<JsApiPreOrderDto>> JsApiPreOrder(JsApiPreOrderQuery query)
        {
            ResultDto<JsApiPreOrderDto> dto = new ResultDto<JsApiPreOrderDto>();
            try
            {
                // 生成订单10位序列号，此处用时间和随机数生成，商户根据自己调整，保证唯一
                string sp_billno = string.Format("{0}{1}{2}", TenPayV3Info.MchId/*10位*/, SystemTime.Now.ToString("yyyyMMddHHmmss"),
                        TenPayV3Util.BuildRandomStr(6));
                int price = (int)(query.PaymentAmount * 100);//单位：分
                string currency = string.IsNullOrEmpty(query.CurrencyType) ? "CNY" : query.CurrencyType;
                //请求信息
                TransactionsRequestData jsApiRequestData = new TransactionsRequestData(TenPayV3Info.AppId, TenPayV3Info.MchId, query.Name, sp_billno, new TenpayDateTime(DateTime.Now.AddHours(30), false), null, TenPayV3Info.TenPayV3Notify, null, new TransactionsRequestData.Amount() { currency = currency, total = price }, new TransactionsRequestData.Payer(query.Openid), null, null, null);
                //请求接口
                var result = await _basePayApis.JsApiAsync(jsApiRequestData);
                //判断是否成功
                if (result.VerifySignSuccess != true)
                {

                    dto.IsSuccess = false;
                    dto.Code = HttpResultCode.Fail;
                    dto.Message = string.IsNullOrEmpty(result.ResultCode.ErrorMessage) ? "获取 prepay_id 结果校验出错！" : result.ResultCode.ErrorMessage;
                    return dto;
                }
                //获取 UI 信息包
                var jsApiUiPackage = TenPaySignHelper.GetJsApiUiPackage(TenPayV3Info.AppId, result.prepay_id);
                if (!string.IsNullOrEmpty(jsApiUiPackage.Signature))
                {
                    dto.IsSuccess = true;
                    dto.Code = HttpResultCode.Success;
                    dto.Message = "获取成功！";
                    JsApiPreOrderDto jsApiPreOrderDto = new JsApiPreOrderDto();
                    jsApiPreOrderDto.appId = jsApiUiPackage.AppId;
                    jsApiPreOrderDto.timeStamp = jsApiUiPackage.Timestamp;
                    jsApiPreOrderDto.signType = "RSA";
                    jsApiPreOrderDto.package = jsApiUiPackage.PrepayIdPackage;
                    jsApiPreOrderDto.paySign = jsApiUiPackage.Signature;
                    jsApiPreOrderDto.nonceStr = jsApiUiPackage.NonceStr;
                    jsApiPreOrderDto.orderId = sp_billno;
                    dto.Data = jsApiPreOrderDto;
                }
                else
                {
                    dto.IsSuccess = false;
                    dto.Code = HttpResultCode.Fail;
                    dto.Message = "获取加密数据出错！";
                }
            }
            catch (Exception ex)
            {
                dto.IsSuccess = false;
                dto.Code = HttpResultCode.Error;
                dto.Message = ex.Message;
            }
            return dto;
        }

        /// <summary>
        /// 根据商户订单Id获取订单信息
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>

        public async Task<ResultDto<OrderReturnJson>> OrderQueryByOutTradeNo(GetOrderInfoQuery query)
        {
            ResultDto<OrderReturnJson> dto = new ResultDto<OrderReturnJson>();
            try
            {
                if (string.IsNullOrEmpty(query.OrderId))
                {
                    dto.IsSuccess = false;
                    dto.Code = HttpResultCode.Fail;
                    dto.Message = "商户订单Id不能为空！";
                    return dto;
                }
                var orderinfo = await _basePayApis.OrderQueryByOutTradeNoAsync(query.OrderId, TenPayV3Info.MchId);
                if (orderinfo.VerifySignSuccess != true)
                {

                    dto.IsSuccess = false;
                    dto.Code = HttpResultCode.Fail;
                    dto.Message = "未查询到相关订单信息！";
                    return dto;
                }
                dto.IsSuccess = true;
                dto.Code = HttpResultCode.Success;
                dto.Message = "查询成功！";
                dto.Data = orderinfo;
            }
            catch (Exception ex)
            {
                dto.IsSuccess = false;
                dto.Code = HttpResultCode.Error;
                dto.Message = ex.Message;
            }
            return dto;
        }

        /// <summary>
        /// 根据微信支付订单Id获取订单信息
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>

        public async Task<ResultDto<OrderReturnJson>> OrderQueryByTransactionId(GetOrderInfoQuery query)
        {
            ResultDto<OrderReturnJson> dto = new ResultDto<OrderReturnJson>();
            try
            {
                if (string.IsNullOrEmpty(query.OrderId))
                {
                    dto.IsSuccess = false;
                    dto.Code = HttpResultCode.Fail;
                    dto.Message = "商户订单Id不能为空！";
                    return dto;
                }
                var orderinfo = await _basePayApis.OrderQueryByTransactionIdAsync(query.OrderId, TenPayV3Info.MchId);
                if (orderinfo.VerifySignSuccess != true)
                {

                    dto.IsSuccess = false;
                    dto.Code = HttpResultCode.Fail;
                    dto.Message = "未查询到相关订单信息！";
                    return dto;
                }
                dto.IsSuccess = true;
                dto.Code = HttpResultCode.Success;
                dto.Message = "查询成功！";
                dto.Data = orderinfo;
            }
            catch (Exception ex)
            {
                dto.IsSuccess = false;
                dto.Code = HttpResultCode.Error;
                dto.Message = ex.Message;
            }
            return dto;
        }

        /// <summary>
        ///退款 
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>

        public async Task<ResultDto<RefundDto>> Refund(RefundQuery query)
        {
            ResultDto<RefundDto> dto = new ResultDto<RefundDto>();
            try
            {
                int total = 0;
                string currency = "";
                if (string.IsNullOrEmpty(query.TransactionId) && string.IsNullOrEmpty(query.OutTradeNo))
                {
                    dto.IsSuccess = false;
                    dto.Code = HttpResultCode.Fail;
                    dto.Message = " TransactionId与OutTradeNo二选一传入";
                    return dto;
                }
                else
                {
                    if (!string.IsNullOrEmpty(query.TransactionId))
                    {
                        //微信支付订单号查询获取金额
                        var orderinfo = await _basePayApis.OrderQueryByTransactionIdAsync(query.TransactionId, TenPayV3Info.MchId);
                        if (orderinfo.VerifySignSuccess == true)
                        {
                            total = orderinfo.amount.total;
                            currency = orderinfo.amount.currency;
                        }
                    }
                    else
                    {
                        //商户订单号查询获取金额
                        var orderinfo = await _basePayApis.OrderQueryByOutTradeNoAsync(query.OutTradeNo, TenPayV3Info.MchId);
                        if (orderinfo.VerifySignSuccess == true)
                        {
                            total = orderinfo.amount.total;
                            currency = orderinfo.amount.currency;
                        }
                    }
                }
                if (total == 0)
                {
                    dto.IsSuccess = false;
                    dto.Code = HttpResultCode.Fail;
                    dto.Message = "未查询到相关订单信息！";
                    return dto;
                }
                // 生成订单10位序列号，此处用时间和随机数生成，商户根据自己调整，保证唯一
                string sp_billno = string.Format("{0}{1}{2}", TenPayV3Info.MchId/*10位*/, SystemTime.Now.ToString("yyyyMMddHHmmss"),
                        TenPayV3Util.BuildRandomStr(6));
                int price = (int)(query.Amount * 100);//单位：分

                var TransactionId = string.IsNullOrEmpty(query.TransactionId) ? null : query.TransactionId;
                var OutTradeNo = string.IsNullOrEmpty(query.OutTradeNo) ? null : query.OutTradeNo;
                //请求参数
                RefundRequsetData refundRequset = new RefundRequsetData(TransactionId, OutTradeNo, sp_billno, query.Reason, TenPayV3Info.TenPayV3Notify, null,
                    new RefundRequsetData.Amount()
                    {
                        refund = price,
                        from = null,
                        currency = currency,
                        total = total
                    }, null);
                //请求接口
                var result = await _basePayApis.RefundAsync(refundRequset);

                //判断是否成功
                if (result.VerifySignSuccess != true)
                {

                    dto.IsSuccess = false;
                    dto.Code = HttpResultCode.Fail;
                    var wx = WeiXinApi.JsonStrToDictionaryValue(result.ResultCode.Additional, "message");
                    //前面为空，值就赋值后面的值
                    dto.Message = wx ?? result.ResultCode.ErrorMessage;
                    return dto;
                }
                dto.IsSuccess = true;
                dto.Code = HttpResultCode.Success;
                dto.Message = "请求成功！";
                dto.Data = new RefundDto() { RefundOrderId = sp_billno };
            }
            catch (Exception ex)
            {
                dto.IsSuccess = false;
                dto.Code = HttpResultCode.Error;
                dto.Message = ex.Message;
            }
            return dto;
        }

        /// <summary>
        ///退款查询
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>

        public async Task<ResultDto<RefundInfoDto>> RefundQuery(RefundQueryQuery query)
        {
            ResultDto<RefundInfoDto> dto = new ResultDto<RefundInfoDto>();
            try
            {
                var result = await _basePayApis.RefundQueryAsync(query.RefundOrderId);
                //判断是否成功
                if (result.VerifySignSuccess != true)
                {

                    dto.IsSuccess = false;
                    dto.Code = HttpResultCode.Fail;
                    dto.Message = string.IsNullOrEmpty(result.ResultCode.ErrorMessage) ? "退款订单号查询失败" : result.ResultCode.ErrorMessage;
                    return dto;
                }
                //SUCCESS：退款成功
                //CLOSED：退款关闭
                //PROCESSING：退款处理中
                //ABNORMAL：退款异常
                if (result.status.Equals("SUCCESS"))
                {
                    dto.IsSuccess = true;
                    dto.Code = HttpResultCode.Success;
                    dto.Message = "查询成功！！";
                    RefundInfoDto infoDto = new RefundInfoDto();
                    infoDto.RefundId = result.refund_id;
                    infoDto.OutRefundNo = result.out_refund_no;
                    infoDto.TransactionId = result.transaction_id;
                    infoDto.OutTradeNo = result.out_trade_no;
                    infoDto.CreateTime = result.create_time;
                    infoDto.SuccessTime = result.success_time.ToString();
                    infoDto.Status = true;
                    infoDto.StatusMessage = "退款成功";
                    infoDto.Refund = ((double)result.amount.refund / 100).ToString("f2");
                    infoDto.Total = ((double)result.amount.total / 100).ToString("f2");
                    dto.Data = infoDto;
                }
                else
                {
                    dto.IsSuccess = false;
                    dto.Code = HttpResultCode.Fail;
                    string meg = "";
                    switch (result.status)
                    {
                        case "CLOSED": meg = "退款关闭"; break;
                        case "PROCESSING": meg = "退款处理中"; break;
                        case "ABNORMAL": meg = "退款异常"; break;
                        default:
                            meg = "未知提示！"; break;
                    }
                    dto.Message = meg;
                }
            }
            catch (Exception ex)
            {
                dto.IsSuccess = false;
                dto.Code = HttpResultCode.Error;
                dto.Message = ex.Message;
            }
            return dto;
        }
    }
}
